import React, { useState, useEffect } from "react";
import {
  Box,
  Dialog,
  DialogActions,
  RadioGroup,
  Radio,
  DialogContent,
  DialogContentText,
  TextField,
  DialogTitle,
  FormControlLabel,
  Stack,
  Button,
  Typography,
  Avatar,
  Input,
} from "@mui/material";

import { useSnackbar } from "notistack";
import request from "../../../api/index";
import { useDispatch, } from 'react-redux'
import { updateUserInfo } from '../../store/models/counterSlice'
import { useRef } from "react";

function useInput() {
  const [value, setvalue] = useState("");
  const ref = useRef(null)
  useEffect(() => {
    setvalue(ref.current || '');
  }, []);
  const onChange = (e) => {
    setvalue(e.target.value);
  };
  const update = (val) => {
    setvalue(val)
    ref.current = val
  }
  return {
    value,
    update,
    onChange,
  };
}

function createState(model, cb) {
  let states = { ...model };
  for (let key in states) {
    states[key] = cb();
  }
  return states;
}

function updateState(state,newState){
  for(let key in state){
    let value = newState[key]
    if(value !== undefined && value !== null){
      state[key].update(value)
    }
  }
}

function getStateValue(model, states) {
  let values = { ...model };
  for (let key in values) {
    if(states[key]){
      values[key] = states[key].value;
    }
  }
  return values;
}




function Profile(props) {
  const [open, setopen] = useState(false);
  const profileModel = {
    nickname: "昵称",
    sex: "性别",
    birthday: "生日",
    phoneNumber: "电话",
    email: "邮箱",
  };

  let proState = createState(profileModel, useInput);
  const { enqueueSnackbar } = useSnackbar();
  
  const handleClose = () => {
    setopen(false);
  };
  
  const handleOpen = () => {
    setopen(true);
  };
  props.profileRef.current = {
    handleOpen
  }
  const {userInfo} = props

  const [avatarPic,setavatarPic] = useState(props.avatarPic)

  const iptRef = useRef(null)
  
  useEffect(() => {
    if(userInfo){
      updateState(proState,userInfo)
    }
  },[])

  useEffect(() => {
    if(userInfo){
      updateState(proState,userInfo)
    }
    setavatarPic(props.avatarPic)
  },[open])

  const handleClickAvatar = async (e) => {
    let files = e.target.files
    let src = URL.createObjectURL(files[0])
    setavatarPic(src)
  };


  const handleUpdate = async () => {

    let resVal = getStateValue(profileModel,proState)
    let formData = new FormData()
    let files = iptRef.current.files || []

    for(let file of files){
      console.log(file);
      formData.append('files',file)
    }

    Object.keys(resVal).forEach((key) => {
      formData.append(key,resVal[key])
    })

    const res = await request.updateUserInfo(formData);

    if (res.code === 200) {
      enqueueSnackbar("更新成功!", { variant: "success" });
      props.getUserInfo()
    } else {
      enqueueSnackbar(res.message, { variant: "warning" });
    }
    handleClose();
  };
      

  return (
    <>
      <React.Fragment>
        <Dialog open={open} onClose={handleClose}>
          <DialogTitle sx={{ display:"flex",flexDirection:'column',alignItems:'center' }} color="HighlightText">
            <div style={{position:'relative'}}>
              <Avatar  sx={{ width: 100, height: 100 }} alt={userInfo?.nickname}  src={avatarPic} onClick={handleClickAvatar} />
              <input ref={iptRef} onChange={handleClickAvatar} type="file" style={{opacity:0,cursor:'pointer',display:'block',position:'absolute',top:0,left:0,width:'100%',height:'100%'}}/>

            </div>
            <Typography pt={2}>{userInfo?.nickname}</Typography>
          </DialogTitle>
          <DialogContent>
            {
              Object.keys(proState).map((key, index) => {
                let {value,onChange} = proState[key]
                return key !== 'sex' ?
                (
                  <Box py={1} key={index}>
                      <span style={{verticalAlign:'baseline'}}>{profileModel[key]}:&nbsp;&nbsp;&nbsp;</span>
                      <Input
                        sx={{minWidth:'30vw'}}
                        autoComplete="off"
                        type="text"
                        margin="dense"
                        value={value}
                        onChange={onChange}
                      />
                  </Box>
                  
                )
                :
                (
                  <Stack
                    key={index}
                    direction="row"
                    spacing={1}
                    alignItems="center"
                  >
                    <Typography> 性别:</Typography>
                    <RadioGroup
                      row
                      value={value}
                      onChange={onChange}
                      aria-labelledby="demo-radio-buttons-group-label"
                      defaultValue="0"
                      name="radio-buttons-group"
                    >
                      <FormControlLabel
                        value="0"
                        control={<Radio />}
                        label="男"
                      />
                      <FormControlLabel
                        value="1"
                        control={<Radio />}
                        label="女"
                      />
                    </RadioGroup>
                  </Stack>
                )
              })
            }


          </DialogContent>
          <DialogActions>
            <Button variant="contained" onClick={handleUpdate}>
              确定
            </Button>
            <Button variant="outlined" onClick={handleClose}>
              取消
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    </>
  )
}

function RegisterView(props) {
  let { handleLoginOpen, handleClose, open } = props;

  const { enqueueSnackbar } = useSnackbar();

  const handleOnClose = () => {
    console.log("close");
  };
  const regModel = {
    userName: "用户名",
    password: "密码",
    password1: "确认密码",
    nickname: "昵称",
    sex: "性别",
    birthday: "生日",
    phoneNumber: "电话",
    email: "邮箱",
  };

  const regState = createState(regModel, useInput.bind(this, open));

  const handleRegister = async () => {
    const regVal = getStateValue(regModel, regState);
    const { userName,password,password1,nickname,sex,birthday,phoneNumber,email, } = regVal
    if (!userName) {
      return enqueueSnackbar('用户名不能为空!', { variant: "warning" });
    } else if(!password){
      return enqueueSnackbar('密码不能为空!', { variant: "warning" });
    } else if(!password1){
      return enqueueSnackbar('确认密码不能为空!', { variant: "warning" });
    } else if (password !== password1){
      return enqueueSnackbar('两次密码输入不一致!', { variant: "warning" });
    }





    const res = await request.userRegister(regVal);
    console.log(res);
    if (res.code === 200) {
      enqueueSnackbar("注册成功!", { variant: "success" });
      handleClose();
    } else {
      enqueueSnackbar(res.message, { variant: "warning" });
    }
  };


  useEffect(() => {
    updateState(regState,{
      userName: "",
      password: "",
      password1: "",
      nickname: "",
      sex: 0,
      birthday: "",
      phoneNumber: "",
      email: "",
    })
  },[open])





  return (
    <>
      <React.Fragment>
        <Dialog
          open={open}
          onClose={handleClose}
          onBackdropClick={handleOnClose}
        >
          <DialogTitle sx={{ textAlign: "center" }} color="HighlightText">
            注册
          </DialogTitle>
          <DialogContent>
            {Object.keys(regState).map((key, index) => {
              const {value,onChange} = regState[key]
              return !["sex"].includes(key) ? (
                <TextField
                  key={index}
                  autoComplete="off"
                  autoFocus={index === 0}
                  margin="dense"
                  id={key}
                  label={`${regModel[key]}:`}
                  type={/^password/.test(key) ? "password" : "text"}
                  fullWidth
                  variant="standard"
                  value={value}
                  onChange={onChange}
                  required={['userName','password'].includes(key)}
                />
              ) : (
                <Stack
                  key={index}
                  direction="row"
                  spacing={1}
                  alignItems="center"
                >
                  <Typography> 性别:</Typography>
                  <RadioGroup
                    row
                    value={value}
                    onChange={onChange}
                    aria-labelledby="demo-radio-buttons-group-label"
                    defaultValue="0"
                    name="radio-buttons-group"
                  >
                    <FormControlLabel
                      value="0"
                      control={<Radio />}
                      label="男"
                    />
                    <FormControlLabel
                      value="1"
                      control={<Radio />}
                      label="女"
                    />
                  </RadioGroup>
                </Stack>
              );
            })}
          </DialogContent>
          <DialogActions>
            <Button variant="outlined" onClick={handleLoginOpen}>
              登录
            </Button>
            <Button variant="contained" onClick={handleRegister}>
              注册
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    </>
  );
}

function LoginView(props) {
  let { openPro, handleRegOpen, handleClose, open } = props;

  const { enqueueSnackbar } = useSnackbar();

  const handleOnClose = () => {
    console.log("close");
  };

  const userNameIpt = useInput();
  const passwordIpt = useInput();
  const dispatch = useDispatch()

  const handleLogin = async () => {

    let userName = userNameIpt.value;
    let password = passwordIpt.value;

    if (!userName) {
      return enqueueSnackbar('用户名不能为空!', { variant: "warning" });
    } else if(!password){
      return enqueueSnackbar('密码不能为空!', { variant: "warning" });
    }



    openPro(true);
    const res = await request.userLogin({ userName, password });
    openPro(false);


    if (res.code === 200) {
      enqueueSnackbar("登录成功!", { variant: "success" });

      let token = res.data.accesToken
      delete res.data.accesToken
      let userInfo = JSON.stringify(res.data)
      localStorage.setItem("userInfo", userInfo);
      localStorage.setItem("token", token);

      dispatch(updateUserInfo(res.data))
      handleClose();
    } else {
      enqueueSnackbar(res.message, { variant: "warning" });
    }
  };

  useEffect(() => {
    userNameIpt.update('')
    passwordIpt.update('')
  },[open])

  return (
    <>
      <React.Fragment>
        <Dialog
          open={open}
          onClose={handleClose}
          onBackdropClick={handleOnClose}
        >
          <DialogTitle sx={{ textAlign: "center" }} color="HighlightText">
            登录
          </DialogTitle>
          <DialogContent>
            <DialogContentText>你好! 欢迎使用电视+</DialogContentText>
            <TextField
              autoComplete="off"
              autoFocus
              margin="dense"
              id="name"
              label="用户名:"
              type="text"
              fullWidth
              variant="standard"
              value={userNameIpt.value}
              onChange={(e) => userNameIpt.onChange(e)}
              required
              // helperText='用户名必须是6-12位的字母和数字'
              // error
            />
            <TextField
              autoComplete="off"
              margin="dense"
              id="pwd"
              label="密码:"
              type="password"
              fullWidth
              variant="standard"
              value={passwordIpt.value}
              onChange={passwordIpt.onChange}
              required
            />
          </DialogContent>
          <DialogActions>
            <Button variant="contained" onClick={handleLogin}>
              登录
            </Button>
            <Button variant="outlined" onClick={handleRegOpen}>
              注册
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    </>
  );
}

export { LoginView, RegisterView, Profile };
